﻿using System.Drawing.Printing;
using System.Security.Claims;
using ZenSystemService.Api.Domain;
using ZenSystemService.Api.Services;

namespace ZenSystemService.Api.Common.Auth
{
    public static class ClaimsPrincipleExtensions
    {
        private static ThreadLocal<UserService> _userService =
            new ThreadLocal<UserService>(() => null);

        public static void SetUserService(UserService userService)
        {
            _userService.Value = userService;
        }
        public static void ClearUserService()
        {
            if (_userService.IsValueCreated)
            {
                _userService.Value = null;
            }
        }
        public static UserModel ToUserModel(this ClaimsPrincipal principal)
        {
            try
            {
                if (principal == null)
                    return null;
                var userIdClaimValue = principal.FindFirstValue(UserClaimTypes.UserId);
                if (userIdClaimValue == null)
                    return null;
                var userId = int.Parse(userIdClaimValue);
                var user = _userService.Value.GetUserByIdAsync(userId).Result;
                if (user == null)
                    throw new Exception("Cannot find this user");
                return new UserModel
                {
                    UserId = userId,
                    //InstitutionId = user.InstitutionId.Value,
                    InstitutionId = user.InstitutionId.HasValue ? user.InstitutionId.Value:0,
                    Username = user.Username,
                    IsDefaultAdmin = user.UserRoles.Any(ur => ur.Role != null && ur.Role.Name == "Admin"),
                    IsCoach = user.UserRoles.Any(ur => ur.Role != null && ur.Role.Name == "Coach"),
                    IsTrainee = user.UserType == "1",
                    IsSuperAdmin = user.UserRoles.Any(ur => ur.Role != null && ur.Role.Name == "SuperAdmin")
                };
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        public static IEnumerable<ProductModel> GetCurrentProducts(this ClaimsPrincipal principal)
        {
            if (principal == null)
                return null;
            var uniqueNumberClaimValues = principal.FindFirstValue(ProductClaimTypes.ProductUniqueNumbers);
            if (uniqueNumberClaimValues == null)
                return null;
            var uniqueNumbers = uniqueNumberClaimValues.Split(',');
            if (uniqueNumbers == null || uniqueNumbers.Length == 0)
                return null;
            var result = new List<ProductModel>();
            foreach (var uniqueNumber in uniqueNumbers)
            {
                var productModel = new ProductModel
                {
                    UniqueNumber = uniqueNumber.Trim(),
                };
                result.Add(productModel);
            }
            return result;
        }
    }
}
